/**
=========================================================
* Material Dashboard 2 React - v2.2.0
=========================================================

* Product Page: https://www.creative-tim.com/product/material-dashboard-react
* Copyright 2023 Creative Tim (https://www.creative-tim.com)

Coded by www.creative-tim.com

 =========================================================

* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/

import { useEffect, useState } from "react";

// @mui material components
import Card from "@mui/material/Card";
import Switch from "@mui/material/Switch";

// Material Dashboard 2 React components
import MDBox from "components/MDBox";
import MDTypography from "components/MDTypography";
import axios from "axios";
import Grid from "@mui/material/Grid";
import MDButton from "../../../../components/MDButton";
import { useNavigate } from "react-router-dom";

function PlatformSettings() {
  // const [followsMe, setFollowsMe] = useState(true);
  // const [answersPost, setAnswersPost] = useState(false);
  // const [mentionsMe, setMentionsMe] = useState(true);
  // const [newLaunches, setNewLaunches] = useState(false);
  // const [productUpdate, setProductUpdate] = useState(true);
  // const [newsletter, setNewsletter] = useState(false);

  const [shouCang, setShouCang] = useState([]);

  const navigate = useNavigate();

  // 使用 useEffect 获取数据
  useEffect(() => {
    const token = localStorage.getItem("authToken");
    const fetchData = async () => {
      try {
        const response = await axios.get("http://localhost:8848/shouCang/shouCangFindById", {
          headers: {
            Authorization: `Bearer ${token}`, // 添加 Bearer 前缀
          },
          withCredentials: true,
        });
        console.log("收藏数据:", response.data);
        // console.log("User data:", response.data);
        if (response.data) {
          setShouCang(response.data);
        } else {
          console.error("User data is not available.");
        }
        /*alert(response.data.data.id);*/
      } catch (error) {
        console.error("获取数据失败:", error);
      }
    };

    fetchData();
  }, []);

  const unfavorite = async (item) => {
    try {
      const token = localStorage.getItem("authToken");
      const response = await axios.delete("http://localhost:8848/shouCang/deleteShouCang", {
        headers: {
          Authorization: `Bearer ${token}`, // 携带 token
        },
        params: { name: item.name }, // 传递参数
      });

      if (response.status === 200) {
        alert("删除成功！");
      }
      window.location.reload();
    } catch (error) {
      console.error("取消收藏失败:", error);
    }
  };

  const parity = async (item1, item2) => {
    try {
      console.log("name是:", item1);
      console.log("table是:", item2);
      const token = localStorage.getItem("authToken");
      const response = await axios.get("http://localhost:8848/warehouse/compare", {
        headers: {
          Authorization: `Bearer ${token}`,
        },
        params: {
          name: item1,
          table: item2,
        },
      });
      navigate("/parity", {
        state: { product: response.data },
      });
      console.log(response);
      await axios.post(
        "http://localhost:8848/addLog",
        {
          operate: "查看了比价图",
        },
        {
          headers: { Authorization: `Bearer ${token}` }, // 发送请求时携带 Token
          withCredentials: true,
        }
      );
    } catch (error) {
      console.error("似乎出错了，请刷新页面重试！", error);
    }
  };

  return (
    <Card sx={{ boxShadow: "none" }}>
      <MDBox p={2}>
        <MDTypography variant="h6" fontWeight="medium" textTransform="capitalize">
          收藏
        </MDTypography>
        <Grid container spacing={3}>
          {shouCang.map((item, index) => (
            <Grid xs={12} sm={6} md={4} key={index}>
              <MDBox
                display="flex"
                flexDirection="column"
                alignItems="center"
                p={2}
                borderRadius={2}
                shadow={2}
              >
                <img src={item.image} alt="商品图片" style={{ width: "50px", height: "50px" }} />
                <MDTypography variant="h20" gutterBottom>
                  {item.name}
                </MDTypography>
                <MDTypography variant="body1" color="primary">
                  价格: {item.oldPrice}
                </MDTypography>
                <MDButton variant="contained" color={"primary"} onClick={() => unfavorite(item)}>
                  取消收藏
                </MDButton>
                <MDButton
                  variant="contained"
                  color={"info"}
                  onClick={() => parity(item.name, item.tableId)}
                >
                  比价
                </MDButton>
              </MDBox>
            </Grid>
          ))}
        </Grid>
      </MDBox>

      {/*  <MDBox pt={1} pb={2} px={2} lineHeight={1.25}>
        <MDTypography variant="caption" fontWeight="bold" color="text" textTransform="uppercase">
          account
        </MDTypography>
        <MDBox display="flex" alignItems="center" mb={0.5} ml={-1.5}>
          <MDBox mt={0.5}>
            <Switch checked={followsMe} onChange={() => setFollowsMe(!followsMe)} />
          </MDBox>
          <MDBox width="80%" ml={0.5}>
            <MDTypography variant="button" fontWeight="regular" color="text">
              Email me when someone follows me
            </MDTypography>
          </MDBox>
        </MDBox>
        <MDBox display="flex" alignItems="center" mb={0.5} ml={-1.5}>
          <MDBox mt={0.5}>
            <Switch checked={answersPost} onChange={() => setAnswersPost(!answersPost)} />
          </MDBox>
          <MDBox width="80%" ml={0.5}>
            <MDTypography variant="button" fontWeight="regular" color="text">
              Email me when someone answers on my post
            </MDTypography>
          </MDBox>
        </MDBox>
        <MDBox display="flex" alignItems="center" mb={0.5} ml={-1.5}>
          <MDBox mt={0.5}>
            <Switch checked={mentionsMe} onChange={() => setMentionsMe(!mentionsMe)} />
          </MDBox>
          <MDBox width="80%" ml={0.5}>
            <MDTypography variant="button" fontWeight="regular" color="text">
              Email me when someone mentions me
            </MDTypography>
          </MDBox>
        </MDBox>
        <MDBox mt={3}>
          <MDTypography variant="caption" fontWeight="bold" color="text" textTransform="uppercase">
            application
          </MDTypography>
        </MDBox>
        <MDBox display="flex" alignItems="center" mb={0.5} ml={-1.5}>
          <MDBox mt={0.5}>
            <Switch checked={newLaunches} onChange={() => setNewLaunches(!newLaunches)} />
          </MDBox>
          <MDBox width="80%" ml={0.5}>
            <MDTypography variant="button" fontWeight="regular" color="text">
              New launches and projects
            </MDTypography>
          </MDBox>
        </MDBox>
        <MDBox display="flex" alignItems="center" mb={0.5} ml={-1.5}>
          <MDBox mt={0.5}>
            <Switch checked={productUpdate} onChange={() => setProductUpdate(!productUpdate)} />
          </MDBox>
          <MDBox width="80%" ml={0.5}>
            <MDTypography variant="button" fontWeight="regular" color="text">
              Monthly product updates
            </MDTypography>
          </MDBox>
        </MDBox>
        <MDBox display="flex" alignItems="center" mb={0.5} ml={-1.5}>
          <MDBox mt={0.5}>
            <Switch checked={newsletter} onChange={() => setNewsletter(!newsletter)} />
          </MDBox>
          <MDBox width="80%" ml={0.5}>
            <MDTypography variant="button" fontWeight="regular" color="text">
              Subscribe to newsletter
            </MDTypography>
          </MDBox>
        </MDBox>
      </MDBox>*/}
    </Card>
  );
}

export default PlatformSettings;
